﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
using System.Threading;

namespace UI.TestModule
{
    public partial class TestForm : Form
    {
        private List<TestChannel> testChannels;
        private string savepath = "";
        public bool IsNumeric(string value)
        {
            return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
        }
        public TestForm(List<TestChannel> channels)
        {
            InitializeComponent();
            InitDateTable(channels);
            
        }

        public void InitDateTable(List<TestChannel> channels)
        {
            testChannels = channels;
            dataGridView1.Columns.Add("Voltage", "测试电压");
            foreach (TestChannel tc in testChannels)
            {
                dataGridView1.Columns.Add(tc.Id.ToString(), tc.ChannelName);
            }
            dataGridView1.Columns.Add("Time", "测试时间");
            DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
            btn.Name = "btnTest";
            btn.HeaderText = "按钮";
            btn.DefaultCellStyle.NullValue = "采集";
            dataGridView1.Columns.Add(btn);
            dataGridView1.Rows.Add();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //点击button按钮事件
            if (dataGridView1.Columns[e.ColumnIndex].Name == "btnTest" && e.RowIndex >= 0)
            {
                //说明点击的列是DataGridViewButtonColumn列
                int rowid = e.RowIndex;
                if (dataGridView1.Rows[rowid].Cells[0].Value != null)
                {
                    if (IsNumeric(dataGridView1.Rows[rowid].Cells[0].Value.ToString()))
                    {
                        for (int i = 0; i < testChannels.Count; i++)
                        {
                            int id = testChannels[i].Id;
                            ChannelType type = testChannels[i].Type;
                            switch (type)
                            {
                                case ChannelType.Acceleration:
                                    dataGridView1.Rows[rowid].Cells[i + 1].Value = GlobalVariable.AccCurrent.CHAccData[id].AverageVol;                                   
                                    break;
                                case ChannelType.Displacement:
                                    dataGridView1.Rows[rowid].Cells[i + 1].Value = GlobalVariable.DptCurrent.CHDisData[id].GapVoltage;
                                    break;
                                default:

                                    break;
                            }
                        }
                        dataGridView1.Rows[rowid].Cells[dataGridView1.Columns.Count - 2].Value = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

                    }
                }
                
            }
        }

        private void 新建测试任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Add();
        }

        private void 保存数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (savepath == "")
            {
                SaveFileDialog dialog = new SaveFileDialog();
                string file = "";
                dialog.Title = "保存测试数据";
                dialog.Filter = "配置文件(*.xlsx)|*.xlsx";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    FileStream fs1 = new FileStream(dialog.FileName, FileMode.Create, FileAccess.Write);
                    fs1.Close();
                }
                savepath = dialog.FileName;
                Task.Run(() => SaveData(savepath));
            }
            else
                Task.Run(() => SaveData(savepath));

        }
        private void SaveData(string saveFileName)
        {
            //Thread.Sleep(1000);
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，您的电脑可能未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
            //写入标题             
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            { worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; }
            //写入数值
            for (int r = 0; r < dataGridView1.Rows.Count; r++)
            {
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    if (i == 3)//将这一列有前导零的加上一个单引号
                    {
                        worksheet.Cells[r + 2, i + 1] = "'" + dataGridView1.Rows[r].Cells[i].Value;
                        string temp = "'" + dataGridView1.Rows[r].Cells[i].Value;//看下值
                    }
                    else
                    {
                        worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
                    }

                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
            MessageBox.Show(saveFileName + "资料保存成功", "提示", MessageBoxButtons.OK);
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);  //fileSaved = true;                 
                }
                catch (Exception ex)
                {//fileSaved = false;                      
                    MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();//强行销毁           
     
        }
        
    }
}
